package biznussoft.fieldservice360.fragments;

import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import biznussoft.fieldservice360.HomeActivity;
import biznussoft.fieldservice360.R;
import biznussoft.fieldservice360.listeners.DialogListener;
import biznussoft.fieldservice360.listeners.GlobalListener;
import biznussoft.fieldservice360.model.Bean_Class;
import biznussoft.fieldservice360.model.ExpensesModel;
import biznussoft.fieldservice360.utils.Session;

import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class ExpensesFragment extends BaseFragment implements OnClickListener{
	private TextView tvSerialNumber,tvTechnician,tvExpenseType,tvAmount,tvDescription,tvTransactionDate,tvActivty;
	private EditText etAmount,etDescription,etTransactionDate;
	private Spinner spType;
	private RestClient client;
	private CheckBox editBillable,billable;
	private DialogListener listener;
	private LinearLayout viewMode,editMode;
	private ExpensesModel model;
	private Button save;
	private String id;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.expenses_detail_fragment, null);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		
		MenuItem addContact = menu.add("Edit");
		MenuItemCompat.setShowAsAction(addContact, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addContact.setIcon(R.drawable.edit); 
		MenuItem actionItem = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		actionItem.setIcon(R.drawable.logout); 
		super.onCreateOptionsMenu(menu, inflater);
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getTitle().equals("Logout")){
			SalesforceSDKManager.getInstance().logout(getActivity());}
		/*if(item.getTitle().equals("Expenses")){
			viewMode.setVisibility(View.GONE);
			editMode.setVisibility(View.VISIBLE);
		}*/
		if(item.getTitle().equals("Edit")){
			viewMode.setVisibility(View.GONE);
			editMode.setVisibility(View.VISIBLE);
			if(billable.isChecked()){
				editBillable.setChecked(true);
			}else{
				editBillable.setChecked(false);
			}
			etAmount.setText(model.getAmount());
			etDescription.setText(model.getDiscription());
			etTransactionDate.setText(model.getTechnicianDate());
			tvActivty.setText(model.getActivity());
		}
		return super.onOptionsItemSelected(item);
	}
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		listener = (DialogListener) getActivity();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		client =  HomeActivity.mActivity.client;
		etAmount = (EditText)getView().findViewById(R.id.etAmount);
		etDescription = (EditText)getView().findViewById(R.id.etDescription);
		etTransactionDate = (EditText) getView().findViewById(R.id.ettransactionDate);
		spType = (Spinner) getView().findViewById(R.id.spExpenseType);
		etTransactionDate.setOnClickListener(this);
		save = (Button) getView().findViewById(R.id.save);
		save.setOnClickListener(this);
		viewMode = (LinearLayout) getView().findViewById(R.id.lllayoutexpense_view_mode);
		editMode = (LinearLayout) getView().findViewById(R.id.lllayoutexpense_edit_mode);
		tvSerialNumber = (TextView) getView().findViewById(R.id.tvSerialNo);
		tvTechnician = (TextView) getView().findViewById(R.id.tvtechnician);
		tvExpenseType = (TextView) getView().findViewById(R.id.tvExpenseType);
		tvAmount = (TextView) getView().findViewById(R.id.tvAmount);
		tvDescription = (TextView) getView().findViewById(R.id.tvDescription);
		tvTransactionDate = (TextView) getView().findViewById(R.id.tvTransactiondate);
		tvActivty = (TextView) getView().findViewById(R.id.tvActivity);
		editBillable = (CheckBox) getView().findViewById(R.id.cbeditBillable);
		billable = (CheckBox) getView().findViewById(R.id.cbBillable);
	}



	public void setTransactionDate(String date){

		etTransactionDate.setText(date);
	}

	public void showRecords(int position) {
		model = ExpensesMasterFragment.expenseList.get(position);
		tvTechnician.setText(model.getTechnician());
		tvExpenseType.setText(model.getExpense());
		tvAmount.setText(model.getAmount());
		tvDescription.setText(model.getDiscription());
		tvTransactionDate.setText(model.getTechnicianDate());
		tvActivty.setText(model.getActivity());
		if(model.isBillable()){
			billable.setChecked(true);
		}else{
			billable.setChecked(false);
		}
		id = model.getId();
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.save:
			updateTime(id);
			break;
		case R.id.ettransactionDate:
			Session.sStartTime = true;
			Session.sEndTime = false;
			Session.sActivity = false;
			Session.sTime = false;
			Session.sExpense = true;
			Session.sNewTime = false;
			Session.sNewExpenses = false;
			listener.nextDialog("date");
		default:
			break;
		}
	}

	private void updateTime(String id){
		boolean flag = editBillable.isChecked();
		
		String objectType = "FConnect__Expense__c";                                 
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("FConnect__Expense_Type__c",spType.getSelectedItem().toString());
		fields.put("FConnect__Amount__c",etAmount.getText().toString());
		fields.put("FConnect__Discription__c", etDescription.getText().toString());
		fields.put("FConnect__Billable__c",flag);
		try {
			
			Log.i("NCS","Request 1  is   :"+fields);       
			RestRequest restRequest = RestRequest.getRequestForUpdate(Bean_Class.api_Version,objectType,id,fields);
			Log.i("NCS","Request 2 is   :"+restRequest);

			client.sendAsync(restRequest, new AsyncRequestCallback() {          
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {     
						Log.i("TPT","Response is   :"+result);  
						finishFragment();
					}                                                
					catch (Exception e) {
						Log.i("TPT","Exception is   :"+e.getMessage());                      
					}
				}

				//@Override
				public void onError(Exception exception) {

					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});
		} 
		catch (Exception e) {
			Log.i("NCS","Exception is   :"+e.getMessage());

		}

	}
	public void finishFragment(){
		getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
	}

}
